<?php
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
    exit('Access Denied');
}

$table_er_kami_typegroup = C::t('#erling_kami_apibuy#er_kami_apibuy_typegroup');

if($_GET['action_kami_apibuy']){//处理增删改
    if($_GET['formhash']!= FORMHASH){
        exit('error');
    }
    if($_GET['action_kami_apibuy'] == 'delete'){
        $table_er_kami_type = C::t('#erling_kami_apibuy#er_kami_apibuy_type');
        // 检查是否有子分类，如果有则不允许删除
        $sub_types = $table_er_kami_type->fetch_all(1,1,['group_id'=>$_GET['action_kami_apibuy_tpyegroup_id']]);
        if (!empty($sub_types['total'])) {
            cpmsg('该分组下有子分类，无法删除。', '', 'error');
        }
    } elseif($_GET['action_kami_apibuy'] == 'edit'){
        $data = array(
            'name' => $_POST['name'],
            'status' => intval($_POST['status']),
            'sort' => intval($_POST['sort']),
            'update_time' => TIMESTAMP
        );
        $table_er_kami_typegroup->update($_GET['action_kami_apibuy_tpyegroup_id'], $data);
    } elseif($_GET['action_kami_apibuy'] == 'add'){
        $data = array(
            'name' => $_POST['name'],
            'status' => intval($_POST['status']),
            'sort' => intval($_POST['sort']),
            'create_time' => TIMESTAMP,
            'update_time' => TIMESTAMP
        );
        $table_er_kami_typegroup->insert($data);
    }
    // 刷新
    $url_page = ADMINSCRIPT.'?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_kami_apibuy&pmod=admin_kami_apibuy_typegroup';
    header('Location: '.$url_page);
    exit;
}

$url_page = ADMINSCRIPT.'?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_kami_apibuy&pmod=admin_kami_apibuy_typegroup';

// 获取当前列表
$page = max(1, intval($page));
$pagesize = max($_GET['pagesize']??20, intval($pagesize));
$start = ($page - 1) * $pagesize;

$query = [];
if (!empty($_GET['name'])) {
    $query['name'] = $_GET['name'];
    $url_page .= '&name=' . $_GET['name'];
}


$result = $table_er_kami_typegroup->fetch_all($page, $pagesize, $query);

$kami_list = $result['data'];
$total = $result['total'];

if(!empty($_GET['pagesize'])){
    $url_page .= '&pagesize='.intval($_GET['pagesize']);
}
$multipage = multi($total, $pagesize, $page, $url_page);

include template('erling_kami_apibuy:admin_kami_apibuy_typegroup');